package me.andy.superappsorganizer;

import com.gc.android.market.api.MarketSession;
import com.gc.android.market.api.MarketSession.Callback;
import com.gc.android.market.api.model.Market.AppsRequest;
import com.gc.android.market.api.model.Market.AppsResponse;
import com.gc.android.market.api.model.Market.ResponseContext;

import me.andy.superappsorganizer.control.MarketDataRetriever;
import me.andy.superappsorganizer.model.DataOrganizer;
import me.andy.superappsorganizer.model.SAppsDatabase;
import me.andy.superappsorganizer.model.SuperAppsOrganizerProvider;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SuperappsorganizerActivity extends ListActivity  {
    public static final String TAG = "SuperAppOrganizer";
public String sresponse;
public String sapp;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        String[] projection = { SAppsDatabase.ID, SAppsDatabase.COL_APP_TITLE};
        String[] uiBindFrom = { SAppsDatabase.COL_APP_TITLE };
        int[] uiBindTo = { R.id.title };
                
        Cursor apps =  managedQuery(
                SuperAppsOrganizerProvider.CONTENT_URI, projection, null, null, null);
     
        CursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.list_item, apps,
                uiBindFrom, uiBindTo);
     
        setListAdapter(adapter);
        
        //getApp();
        //String s = MarketData.getMarketData("com.gzl.stardunk");
		
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        String projection[] = { SAppsDatabase.COL_APP_TITLE};
        Cursor appCursor = getContentResolver().query(
                Uri.withAppendedPath(SuperAppsOrganizerProvider.CONTENT_URI,
                        String.valueOf(id)), projection, null, null, null);
        if (appCursor.moveToFirst()) {
            String appName = appCursor.getString(0);
            Log.e(TAG,appName);
            //sapp=appName;
            setProgressBarIndeterminateVisibility(true);
            MarketCategoryTask task = new MarketCategoryTask();
            task.execute(new String[] {appName});
        }
            
           /*new Thread(new Runnable() {
                public void run() {
                	MarketDataRetriever m = new MarketDataRetriever(getApplicationContext(),sapp);
                	sresponse= m.retrieveCategory();
                }
              }).start();
        }
        setProgressBarIndeterminateVisibility(false);
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(getApplicationContext(), sresponse, duration);
		toast.show();
        appCursor.close();*/
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_options, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.itemAdd:
        	loadData();
            return true;
        case R.id.itemDeleteAll:
            deleteAll();
            return true;
        case R.id.itemShowAppGrid:
        	Intent myIntent = new Intent(getBaseContext(), GridAppsActivity.class);
            startActivityForResult(myIntent, 0);
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private void deleteAll() {
    	DataOrganizer dataOrg = new DataOrganizer(getApplicationContext());
    	dataOrg.DumpAll();
		
	}

	private void loadData() {
    	DataOrganizer dataOrg = new DataOrganizer(getApplicationContext());
    	dataOrg.DumpAll();
    	dataOrg.loadData();
    }
	
	private class MarketCategoryTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... apps) {
			String response = "";
			for (String app : apps) {
		            Log.i(TAG,"Retrieving information for: " + app);
		        	MarketDataRetriever m = new MarketDataRetriever(getApplicationContext(),app);
		        	response= m.retrieveCategory();
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			setProgressBarIndeterminateVisibility(false);
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(getApplicationContext(), result, duration);
			toast.show();
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	private void getApp() {

		MarketSession session = new MarketSession();
		String androidId=Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		if (androidId==null) {
			androidId="12";
		}
		session.login("andydev@gmail.com","ch!6319l3");
		session.getContext().setAndroidId(androidId);


		String query = "pname:com.google.android.apps.maps";
		AppsRequest appsRequest = AppsRequest.newBuilder()
				.setQuery(query)
				.setWithExtendedInfo(true)
				.setStartIndex(0).setEntriesCount(1)
				.build();

		session.append(appsRequest, new Callback<AppsResponse>() {
			@Override
			public void onResult(ResponseContext context, AppsResponse response) {
				// Your code here
				// response.getApp(0).getCreator() ...
				// see AppsResponse class definition for more infos
				
				//response.getApp(0).getCreator()
				Log.i(context.toString(),response.getApp(0).getExtendedInfo().getCategory().toString());

			}
		});
		session.flush();
	}

    
}